package com.kx.smartdevice.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kx.smartdevice.constants.ResultCode;
import com.kx.smartdevice.exceptions.AddErrorException;
import com.kx.smartdevice.exceptions.DeleteErrorException;
import com.kx.smartdevice.exceptions.UpdateErrorException;
import com.kx.smartdevice.mapper.UserMapper;
import com.kx.smartdevice.pojo.User;
import com.kx.smartdevice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Author Sun
 * @Date 2021/5/26 15:04
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<User> getAllUsersByPage(int pageNum, int pageSize,String username,int status) {

        //开启分页
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.findAllUsers(username,status);

        //密码信息不返回给前台，把密码每个人的密码置空
        userList.forEach(user->user.setPassword(null));

        //把用户信息保存在PageInfo中
        PageInfo<User> pageInfo = new PageInfo<>(userList);
        return pageInfo;
    }

    @Override
    public void addUser(User user) {
        if(user==null || user.isEmpty()){
            throw new AddErrorException("传递的数据为空,请检查", ResultCode.NULL_DATA);
        }
        Long userId = getUserIdByUserName(user.getUsername());
        if(user.getId() == userId){
            throw new AddErrorException("用户" + user.getUsername() + "已经存在", ResultCode.USER_EXIST_ERROR);
        }
        userMapper.addUser(user);
    }

    @Override
    public Long getUserIdByUserName(String username) {
        if (username == null) {
            return null;
        }
        return userMapper.getUserIdByUserName(username);
    }

    @Override
    public int deleteUserByIds(String[] ids) {
        if(ids==null){
            throw new DeleteErrorException("用户id没有传递", ResultCode.DATA_NOT_ALLOWED);
        }
        try {
            return userMapper.deleteUserByIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DeleteErrorException(e.getMessage(), ResultCode.DATA_NOT_ALLOWED);
        }
    }

    @Override
    public int updateUser(User user) {
        if (user == null) {
            throw new UpdateErrorException("没有传递数据", ResultCode.NULL_DATA);
        }
        int result  = userMapper.updateUser(user);
        return result;
    }

}
